import platform
import subprocess
from pathlib import Path

import requests


def downloadhosts(url):
    with Path('./hosts').open('wb') as file:
        data = requests.get(url)
        file.writelines(data)


def sethost():
    try:
        scripts = {
            'Windows': ['copy %SystemRoot%\System32\drivers\etc\hosts  hosts_bak',
                        'copy hosts %SystemRoot%\System32\drivers\etc\hosts',
                        'ipconfig /flushdns',
                        'pause'],
            'Linue': ['cp /etc/hosts.txt ./hosts_bak',
                      'mv ./hosts /etc/hosts',
                      'pause',
                      'sudo /etc/init.d/networking restart '],
            'Darwin': ['sudo cp /etc/hosts ./host_bak',
                       'sudo mv ./hosts.txt /etc/hosts',
                       'sudo ifconfig en0 down && sudo ifconfig en0 up']
        }.get(platform.system(), 'Windows')

        for script in scripts:
            subprocess.call(script)

        print('Finish! Try your browser!')
    except Exception as e:
        print(e)


if __name__ == '__main__':
    url = 'https://raw.githubusercontent.com/googlehosts/hosts/master/hosts-files/hosts'
    downloadhosts(url=url)
    print('Hosts update success!')
    sethost()
    print('Hosts replaced success!')
